<?php

class Feed_model extends CI_Model {
	
	public function post($author,$bid,$title,$content,$type){
		$date_now = date('Y-m-d H:i:s');
		$data = array(
				'author' => $author,
				'bid' => $bid,
				'title' => $title,
				'content' => $content,
				'posttime' => $date_now,
				'type' => $type,
		);
		$this->db->insert('post', $data);
		return $this->db->insert_id();
	}
	
	public function get($pid){
		$this->db->where('pid',$pid);
		$query = $this->db->get('post');
		return $query->row_array();
	}
	
	public function delete($pid){
		$this->db->delete('post', array('pid' => $pid));
	}
	
	public function share($uid,$bid,$pid,$reason,$recursion=true){
		$orig_post = $this->get($pid);
		if (!$orig_post) {
			echo -1;
		} elseif ($orig_post['type']!='share'||$recursion){
			$this->post($uid, $bid, $reason, $orig_post['pid'], 'share');
		} else {
			$this->share($uid, $bid, $orig_post['content'], $reason);
		}
	}
	
	/**
	 * get all posts from given blog
	 */
	public function get_all_posts($bid,$oder = 'desc'){
		$this->db->where('bid',$bid);
		$this->db->order_by("posttime", $oder);
		$query = $this->db->get('post');
		$posts =  $query->result_array();
		return $posts;
	}
	
	
	/**
	 * get some random  posts from alll the blogs
	 */
	public function random_get($num = 10,$uid){
		$sql = "
				select * from post where
				bid not in (select bid from follow where uid = ?)
				and
				pid not in (select pid from tag where 
					text in (select tag from focus where uid = ?)
			 	) order by rand() limit ?";
		$query = $this->db->query($sql,array($uid,$uid,$num));
		return $query->result_array();
	}
	
	public function home_get($uid){
		$sql = "select * from post where 
				bid in (select bid from follow where uid = ?)
				or
				pid in (select pid from tag where 
					text in (select tag from focus where uid = ?))";
		$query = $this->db->query($sql,array($uid,$uid));
		return $query->result_array();
	}
	
	public function get_direct_share_num($pid){
		$this->db->where('content',$pid);
		$this->db->where('type','share');
		return $this->db->count_all_results("post");
	}
	
	public function get_share_from($pid){
		$this->db->where('content',$pid);
		$this->db->where('type','share');
		return $this->db->get('post')->result_array();
	}
	
	public function get_share_num($pid){
		$ref_posts = $this->get_share_from($pid);
		$num = count($ref_posts);
		if ($num!=0){
			foreach ($ref_posts as $post){
				$num += $this->get_share_num($post['pid']);
			}
		}
		return $num;
	}
}

?>